<?php
class Essence_service extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('novel_model');
        $this->load->model('essence_model');
    }

    public function getLists()
    {
        $essence_lists = $this->essence_model->findAll([
            'fields'        => 'name, template_type as templateType, novel_ids',
            'where'         => [
                'deleted'   => 'N',
                'hide'      => 'N',
            ],
            'order_by'      => [
                'order' => 'desc',
            ],
        ]);
        if (empty($essence_lists))
        {
            return [];
        }
        $this->_fill_essence_list($essence_lists);
        return $essence_lists;
    }

    public function init()
    {
        $temps = $this->essence_model->template_type_book_num;
        array_walk($temps, function($row){
            $insert_data = [
                'id'            => $this->essence_model->getUuid(),
                'name'          => '测试模版',
                'max_book_num'  => $row['num'],
                'template_type' => $row['type'],
                'novel_ids'     => $this->_init_find_novel_ids($row['num']),
                'order'         => rand(1, 100),
                'add_time'      => time(),
                'hide'          => 'N',
            ];
            $this->essence_model->insert($insert_data);
        });
    }

    public function create($name, $type, $novel_ids, &$err)
    {
        if (empty($name) || empty($type) || empty($novel_ids) || mb_strlen($name) > 5)
        {
            $err = [
                'errorCode'     => PARAM_ERR,
                'errorMessage'  => '参数错误',
            ];
            return false;
        }
        $temps = $this->getAllTemps();
        if ( ! in_array($type, $temps))
        {
            $err = [
                'errorCode'     => PARAM_ERR,
                'errorMessage'  => '类型错误',
            ];
            return false;
        }
        $novels = explode(',', $novel_ids);
        $max_num = $this->essence_model->template_type_book_num[$type]['num'];
        if (count($novels) > $max_num || count($novels) < 1)
        {
            $err = [
                'errorCode'     => PARAM_ERR,
                'errorMessage'  => '书籍数量超出',
            ];
            return false;
        }
        $this->essence_model->insert([
            'id'            => $this->essence_model->getUuid(),
            'name'          => $name,
            'max_book_num'  => $max_num,
            'template_type' => $type,
            'novel_ids'     => $novel_ids,
            'order'         => 0,
            'add_time'      => time(),
            'hide'          => 'N',
        ]);
        return true;
    }

    public function markDel($id)
    {
        $params = [
            'where' => [
                'id'    => $id,
            ],
        ];
        $delete = [
            'deleted'   => 'Y',
        ];
        $this->essence_model->update($params, $delete);
        return false;
    }

    public function getAllTemps()
    {
        $_temps = $this->essence_model->template_type_book_num;
        $temps = [];
        foreach($_temps as $key => $value)
        {
            array_push($temps, $value['type']);
        }
        return $temps;
    }

    private function _init_find_novel_ids($num)
    {
        $sql = 'select novel_id from novels where deleted = ? and hide = ? and publish = ? order by rand() limit ?';
        $result = $this->essence_model->db->query($sql, ['N', 'N', 'Y', $num])->result_array();
        $str_novelids = implode(',', array_column($result, 'novel_id'));
        return $str_novelids;
    }

    private function _fill_essence_list(&$essence_lists)
    {
        array_walk($essence_lists, function(&$row) {
            $novel_ids_arr = explode(',', $row['novel_ids']);
            $row['novels'] = $this->_find_novel_detail_by_ids($novel_ids_arr);
        });
    }

    private function _find_novel_detail_by_ids($novel_ids)
    {
        $res = $this->novel_model->findAll([
            'fields'        => 'novel_id as novelId, novel_name as novelName, author_name as authorName, cover_url as coverUrl, intro, tag_name as tagName',
            'where_in'      => [
                'novel_id'      => $novel_ids,
            ],
            'where'         => [
                'hide'      => 'N',
                'deleted'   => 'N',
                'publish'   => 'Y',
            ],
        ]);
        return $res;
    }
}
